package online.foxnull2.foxmall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.JsonSerializable;
import com.fasterxml.jackson.databind.util.JSONPObject;
import lombok.extern.slf4j.Slf4j;
import online.foxnull2.common.to.es.SkuEsModel;
import online.foxnull2.foxmall.search.config.ElasticSearchConfig;
import online.foxnull2.foxmall.search.constant.ESConstant;
import online.foxnull2.foxmall.search.service.ProductSaveService;
import org.apache.tomcat.util.json.JSONParser;
import org.elasticsearch.action.bulk.BulkItemResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ProductSaveServiceImpl implements ProductSaveService {

    private final RestHighLevelClient restHighLevelClient;

    @Autowired
    public ProductSaveServiceImpl(RestHighLevelClient restHighLevelClient) {
        this.restHighLevelClient = restHighLevelClient;
    }

    @Override
    public Boolean productSaveService(List<SkuEsModel> skuEsModels) throws IOException {

        BulkRequest bulkRequest = new BulkRequest();
        skuEsModels.forEach(skuEsModel -> {
            IndexRequest indexRequest = new IndexRequest(ESConstant.PRODUCT_INDEX);
            indexRequest.id(skuEsModel.getSkuId().toString());
            String jsonString = JSON.toJSONString(skuEsModel);
            indexRequest.source(jsonString, XContentType.JSON);
            bulkRequest.add(indexRequest);
        });
        BulkResponse bulkResponse = restHighLevelClient.bulk(bulkRequest, ElasticSearchConfig.COMMON_OPTIONS);

        if (bulkResponse.hasFailures()) {
            List<String> collect = Arrays.stream(bulkResponse.getItems()).filter(BulkItemResponse::isFailed).map(BulkItemResponse::getId).collect(Collectors.toList());
            log.error("product up error -> {}", collect);
        }

        return bulkResponse.hasFailures();
    }

}
